// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: 'product-6d4b5e'
})
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const pro = await db.collection('user_list').where({openid: event.openid}).get();
    if(pro.data.length>0){ //说明数据已存在
      if(event.dz==0||event.dz==1){
        await db.collection('user_list').doc(pro.data[0]._id).update({
          data: {
            dz: event.dz  //0 1
          }
        })
      }
      
    }else{
      await db.collection('user_list').add({
        // data 字段表示需新增的 JSON 数据
        data: {
          openid: event.openid,
          nick_name: event.nick_name,
          gender: event.gender,
          language: event.language,
          city: event.city,
          province: event.province,
          avatar_url: event.avatar_url,
          country: event.country,
          dz: event.dz,
          createtime: event.createtime
        }
      })
    }
    if(event.dz==-1){
      await db.collection('user_info').add({
        // data 字段表示需新增的 JSON 数据
        data: {
          openid: event.openid,
          nick_name: event.nick_name,
          gender: event.gender,
          language: event.language,
          city: event.city,
          province: event.province,
          avatar_url: event.avatar_url,
          country: event.country,
          createtime: event.createtime
        }
      })
    }
    return 0;
    
  } catch (e) {
    console.error(e)
  }
}